﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace OfficeWatermark
{
    public class ImageHelper
    {
        #region instance 构建静态实例
        private static ImageHelper instance;
        private static object lockObject = new object();
        public static ImageHelper Instance
        {
            get
            {
                if (instance == null)
                    lock (lockObject)
                    {
                        if (instance == null)
                        {
                            instance = new ImageHelper();
                        }
                    }
                return instance;
            }
        }
        #endregion


        public void CreateImage(StyleModel model, int maxWidth, int maxHeight)
        {
            int width = maxWidth;
            int height = maxHeight;
            var angle = model.angle;
            if (maxWidth < maxHeight)
            {
                width = maxHeight;
                height = maxWidth;
                angle = model.angle - 90;
            }

            float f = model.fontSize;
            string color = model.fontColor;
            string str = model.showContent;
            int H = CheckH(str);
            int length = (int)(H * 1.38 * (int)f + (str.Length - H) * 0.75 * (int)f);
            int widthSplit = model.widthSplit;
            int heightSplit = model.heightSplit;
            Bitmap image = new Bitmap(maxWidth * 2, maxHeight * 2);
            int widthCount = image.Width / (length + widthSplit) + 1;
            int heightCount = image.Height / ((int)f + heightSplit) + 1;
            Graphics g = Graphics.FromImage(image);
            try
            {
                g.TranslateTransform(0, 0);


                ColorConverter colConvert = new ColorConverter();
                Color fontColor = (Color)colConvert.ConvertFromString(model.fontColor);
                Brush whiteBrush = new SolidBrush(Color.FromArgb(Convert.ToInt32(255 * model.transparency), fontColor));
                Font font = new Font(model.fontStyle, f, FontStyle.Regular);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
                //设置质量
                //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                for (int i = 0; i < widthCount; i++)
                {
                    for (int j = 0; j < heightCount; j++)
                    {
                        g.DrawString(str, font, whiteBrush,
                            (i) * (length + widthSplit) + model.leftSplit,
                            (j) * (heightSplit + (int)f) + model.topSplit);
                    }
                }


                MemoryStream ms = new MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                image.Save(model.imgPath, System.Drawing.Imaging.ImageFormat.Png);
                //if (model.angle % 360 == 0)
                //{
                //    //if (File.Exists(model.imgPath))
                //    //{
                //    //    File.Delete(model.imgPath);
                //    //}
                //    image.Save(model.imgPath, System.Drawing.Imaging.ImageFormat.Png);
                //    image.Dispose();
                //}
                //else
                //{
                //    RotateImage(image, model.imgPath, model.angle, maxWidth, maxHeight);

                //}
            }
            catch (Exception ex)
            {
            }
            finally
            {
                g.Dispose();
                image.Dispose();



            }
        }

        private void RotateImage(Image b, string savePath, float angle, int width, int height)
        {
            angle = angle % 360;            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目标位图
            Image dsImage = new Bitmap(W, H);
            Graphics g = Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;

            //计算偏移量
            Point Offset = new Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域：让图像的中心与窗口的中心点一致
            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
            //恢复图像在水平和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至绘图的所有变换
            g.ResetTransform();
            g.Save();
            g.Dispose();
            ////裁剪图片
            {
                int _width = (dsImage.Width - width) / 2;
                int _height = (dsImage.Height - height) / 2;
                //创建图像
                Rectangle drawRect = new Rectangle(0, 0, width, height);  //绘制整块区域
                System.Drawing.Image tmp = new Bitmap(drawRect.Width, drawRect.Height);           //按指定大小创建位图
                Rectangle AdrawRect = new Rectangle(_width, _height, width, height);
                //绘制
                Graphics gn = Graphics.FromImage(tmp);                   //从位图创建Graphics对象
                gn.Clear(Color.FromArgb(0, 0, 0, 0));                    //清空
                gn.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
                gn.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
                gn.DrawImage(dsImage, drawRect, AdrawRect, GraphicsUnit.Pixel);   //从pic的给定区域进行绘制 
                tmp.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);

                tmp.Dispose();
            }
            dsImage.Dispose();
        }


        public void CreateImageHeight(StyleModel model, int maxWidth, int maxHeight)
        {
            maxWidth = maxWidth > 5000 ? 5000 : maxWidth;
            maxHeight = maxHeight > 5000 ? 5000 : maxHeight;
            string imagePath = model.imgPath;
            if (System.IO.File.Exists(model.imgPath))
            {
                return;
            }
            float f = model.fontSize;
            string color = model.fontColor;
            string str = model.virtualText;
            int H = CheckH(str);
            int length = (int)(H * 1.38 * (int)f + (str.Length - H) * 0.75 * (int)f);
            int widthSplit = model.widthSplit;
            int heightSplit = model.heightSplit;
            int max_ = maxWidth > maxHeight ? maxWidth : maxHeight;
            max_ = (int)(max_ * 1.5);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(max_, max_);
            int widthCount = image.Width / (length + widthSplit) + 1;
            int heightCount = image.Height / ((int)f + heightSplit) + 1;
            Graphics g = Graphics.FromImage(image);
            try
            {
                g.TranslateTransform(0, 0);
                System.Drawing.ColorConverter colConvert = new System.Drawing.ColorConverter();
                Color fontColor = (System.Drawing.Color)colConvert.ConvertFromString(color);
                Font font = new System.Drawing.Font(model.fontStyle,
                    f, System.Drawing.FontStyle.Regular);
                Brush whiteBrush = new SolidBrush(Color.FromArgb(255, fontColor));
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                for (int i = 0; i < widthCount; i++)
                {
                    for (int j = 0; j < heightCount; j++)
                    {
                        g.DrawString(str, font, whiteBrush,
                            (i) * (length + widthSplit) + model.leftSplit,
                            (j) * (heightSplit + (int)f) + model.topSplit);
                    }
                }
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                if (model.angle % 360 == 0)
                {
                    if (System.IO.File.Exists(imagePath))
                    {
                        System.IO.File.Delete(imagePath);
                    }
                    image.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    RotateImageHeight(image, imagePath, model.angle, maxWidth, maxHeight);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        private void RotateImageHeight(System.Drawing.Image b, string savePath, float angle, int width, int height)
        {
            angle = angle % 360;            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            W = W > 10000 ? 9999 : W;
            H = H > 10000 ? 9999 : H;
            //目标位图
            System.Drawing.Image dsImage = new Bitmap(W, H);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            //计算偏移量
            Point Offset = new Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域：让图像的中心与窗口的中心点一致
            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
            //恢复图像在水平和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至绘图的所有变换
            g.ResetTransform();
            g.Save();
            g.Dispose();
            ////裁剪图片
            {
                int _width = (dsImage.Width - width) / 2;
                int _height = (dsImage.Height - height) / 2;

                width = width > 1920 * 2 ? 1920 * 2 : width;
                height = height > 1080 * 2 ? 1080 * 2 : height;

                //创建图像
                Rectangle drawRect = new Rectangle(0, 0, width, height);  //绘制整块区域
                System.Drawing.Image tmp = new Bitmap(drawRect.Width, drawRect.Height);           //按指定大小创建位图
                Rectangle AdrawRect = new Rectangle(_width, _height, width, height);
                //绘制
                Graphics gn = Graphics.FromImage(tmp);                   //从位图创建Graphics对象
                gn.Clear(Color.FromArgb(0, 0, 0, 0));                    //清空
                gn.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                gn.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                gn.DrawImage(dsImage, drawRect, AdrawRect, GraphicsUnit.Pixel);   //从pic的给定区域进行绘制
                if (System.IO.File.Exists(savePath))
                {
                    System.IO.File.Delete(savePath);
                }
                tmp.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
                tmp.Dispose();
            }
            dsImage.Dispose();
        }

        public int CheckH(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }
            List<string> itemList = new List<string>();
            CharEnumerator CEnumerator = str.GetEnumerator();
            Regex regex = new Regex("^[\u4E00-\u9FA5]{0,}$");
            while (CEnumerator.MoveNext())
            {
                if (regex.IsMatch(CEnumerator.Current.ToString(), 0))
                    itemList.Add(CEnumerator.Current.ToString());
            }
            return itemList.Count;
        }
    }
}
